using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class PartBlock : MonoBehaviour
{
    public CallbackPart m_OnDragBeginCallback;
    public CallbackGameObject m_OnDestoryCallback;
    public CallbackPart m_OnRotationBeginCallback;
    public CallbackPart m_OnRotationEndCallback;
    public Part m_Part;
    bool m_IsDraging  = false;
    public bool m_IsConfig = true;
    public ShipGrad m_ShipGrad;
    void Start()
    {
        //GetComponent<RectTransform>().pivot = new Vector2(0.5f, 0.5f);
        m_IsConfig = true;
    }

    // Update is called once per frame
    void Update()
    {
        if(m_IsDraging && m_IsConfig && m_Part != null && Input.GetKeyDown(KeyCode.R))
        {
            if (m_OnRotationBeginCallback != null)
                m_OnRotationBeginCallback(m_Part);  
            m_Part.m_RotationAngle++;
            m_Part.m_RotationAngle = (HexGrid.RotationAngle)((int)m_Part.m_RotationAngle % ((int)HexGrid.RotationAngle.LEFT_60 + 1));

            transform.rotation = Quaternion.Euler(0f, 0f, (int)m_Part.m_RotationAngle * -60f);
            if (m_OnRotationEndCallback != null)   
                m_OnRotationEndCallback(m_Part);
        }
    }
    public void OnDragBegine(BaseEventData eventData)
    {
        if(Input.GetMouseButton(0) && m_IsConfig)
        {
            m_IsDraging = true;
            if (m_OnDragBeginCallback != null)
                m_OnDragBeginCallback(m_Part);
            eventData.selectedObject = gameObject;

            GetComponent<Image>().raycastTarget = false;

            if(m_ShipGrad)
                m_ShipGrad.Selected(this);

        }
        else
        {
            var itemDrager = ItemDrager.Create(m_Part);
            eventData.selectedObject = itemDrager.gameObject;
        }
    }
    public void OnDrag(BaseEventData eventData)
    {
        if(m_IsConfig)
            transform.position = Input.mousePosition;
        else if(eventData.selectedObject)
        {
            eventData.selectedObject.transform.position = Input.mousePosition;
        }
    }
    public void OnDragEnd(BaseEventData eventData)
    {
        m_IsDraging = false;
        if (m_IsConfig)
        {
            eventData.selectedObject = gameObject;
            if (m_OnDestoryCallback != null)
                m_OnDestoryCallback(gameObject);
            Destroy(gameObject);
        }
        else if(eventData.selectedObject && eventData.selectedObject.GetComponent<ItemDrager>())
        {
            Destroy(eventData.selectedObject);
            eventData.selectedObject = null;
        }
    }
    public void OnClicked(BaseEventData eventData)
    {
        if (m_ShipGrad)
            m_ShipGrad.Selected(this);
    }
}
